import {
  Injectable,
  Inject,
  forwardRef,
  HttpException,
  InternalServerErrorException,
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './users.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';
import { RemoveUserDto } from './dto/remove-user.dto';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  // 增加
  async create(createUserDto: CreateUserDto): Promise<any> {
    const { name, password, createdAt } = createUserDto;
    createUserDto.password = password; //cryptoString(password);
    createUserDto.createdAt = createdAt || new Date();
    createUserDto.updatedAt = new Date();

    delete createUserDto.id;

    const isExist = await this.usersRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 0) {
      throw new InternalServerErrorException('用户已存在');
    }

    return await this.usersRepository.save(createUserDto);
  }

  // 删除
  async delete(removeUserDto: RemoveUserDto): Promise<any> {
    const { ids } = removeUserDto;

    return this.usersRepository.delete(ids);
  }

  // 更新
  async update(updateUserData): Promise<any> {
    const updateUserDto = updateUserData;
    updateUserDto.updatedAt = new Date();
    const { name } = updateUserDto;

    const isExist = await this.usersRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 1) {
      return {
        statusCode: 201,
        message: '已存在',
      };
    }

    return await this.usersRepository.update(updateUserDto.id, updateUserDto);
  }

  // 列表
  async findAll(query: any): Promise<any> {
    const { keyword, page = 1, pageSize = 10 } = query;
    const skip = (page - 1) * pageSize;

    let params = {
      skip,
      take: pageSize,
    };

    let whereParams = {};

    if (keyword) {
      whereParams = Object.assign(whereParams, {
        name: Like(`%${keyword}%`),
      });
    }

    params = Object.assign(
      {
        select: [
          'id',
          'name',
          'roles',
          'email',
          'phone',
          'status',
          'intro',
          'createdAt',
        ],
      },
      params,
      {
        where: whereParams,
      },
      {
        order: {
          updatedAt: 'DESC',
        },
      },
    );

    const [data, total] = await this.usersRepository.findAndCount(params);

    return {
      total,
      data,
    };
  }

  // 根据用户名查找
  async findOneByName(username: string): Promise<any> {
    return this.usersRepository.findOne({
      where: {
        name: username,
      },
    });
  }

  // 根据ID查找
  async findOneById(id: string): Promise<any> {
    return this.usersRepository.findOneBy({ id: id });
  }

  // 更新密码
  async updatePassword(data): Promise<any> {
    const body = data;
    const user = await this.usersRepository.findOneBy({ id: body.id });
    const { oldPassword, password: newPassword } = body;
    //oldPassword = cryptoString(oldPassword);
    body.password = newPassword; //cryptoString(newPassword);

    const { password } = user;
    if (password != oldPassword) {
      //旧密码不正确
      throw new HttpException('旧密码不正确', 1);
    } else {
      body.updatedAt = new Date();
      delete body.oldPassword;
      delete body.rePassword;

      return await this.usersRepository.update(body.id, body);
    }
  }

  // 重置密码
  async resetPassword(params, password): Promise<any> {
    const { id } = params;
    const data = {
      password: password,
      updatedAt: new Date(),
    };
    const result = await this.usersRepository.update(id, data);
    return result;
  }

  // 更新头像
  async updateAvatar(params): Promise<any> {
    const updateUserAvatar = params;
    updateUserAvatar.updatedAt = new Date();
    return await this.usersRepository.update(
      updateUserAvatar.id,
      updateUserAvatar,
    );
  }

  // 数量
  async getCount() {
    return await this.usersRepository.count();
  }
}
